package com.jiufen.Filter;



//本项目采用拦截器 interceptor 用作拦截  filter仅做参考  所以注释

import com.jiufen.Utils.CurrentHolder;
import com.jiufen.Utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Slf4j
@WebFilter(urlPatterns = "/*")
@Component
/**
 * 如果@Component 和 @WebFilter(urlPatterns = "/*") 同时存在 拦截器 还会 拦截自己一次  不建议使用 component
 */
public class LoginFilter implements Filter {


    /**
     * 此处无法注入不影响 忽略报错 不影响编译
     */
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1.获取请求
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        // 2.获取请求路径

        String requestURI = httpServletRequest.getRequestURI();
        log.info("拦截到请求:{}", requestURI);

        //3.判断是否是登录请求 准备过滤 如是登录请求 放心 return
        if (requestURI.contains("login") || requestURI.contains("register")) {
            log.info("本次请求不需要处理");
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }

        //4.获取请求头token
        String token = httpServletRequest.getHeader("token");
        log.info("获取请求头token:{}", token);

        //5.判断token是否为空  如果为空 返回响应401 不为空 解析token
        if (token == null) {
            log.info("请求头为空，返回登录页面");
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //6.解析token 失败 返回401
        try {
            Map<String, Object> jwtResult = jwtUtils.parseJwt(token);
            String LoginId = jwtResult.get("id").toString();
            log.info("当前登录ID为:{}",LoginId);
            CurrentHolder.setCurrentId(Integer.parseInt(LoginId));
            log.info("当前员工登录ID为:{},已存入threadLocal",LoginId);

        } catch (Exception e) {
           log.info("token解析失败");
           return;
        }
        //7.成功 放行请求
        log.info("令牌合法 开始放行~");
        filterChain.doFilter(httpServletRequest, httpServletResponse);
        log.info("令牌合法 结束放行~");

        //删除threadLocal中的数据
        CurrentHolder.remove();


    }
}
